package com.swak.reactivex.threads;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

import com.swak.reactivex.threads.waitstrategy.BlockingWaitStrategy;
import com.swak.reactivex.threads.waitstrategy.WakeupWaitStrategy;

/**
 * 定义 EventLoop 的接口.
 * 
 * @author 618lf
 */
public interface EventLoop extends Executor {

	boolean isShuttingDown();

	boolean isShutdown();

	boolean isTerminated();

	CompletableFuture<Void> shutdownGracefully();

	CompletableFuture<Void> shutdownGracefully(long quietPeriod, long timeout, TimeUnit unit);

	CompletableFuture<Void> terminationFuture();

	CompletableFuture<Void> submit(Runnable task);

	<T> CompletableFuture<T> submit(Runnable task, T result);

	void execute(Runnable command);

	void runOnEventLoop(Runnable command);

	ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit);

	ScheduledFuture<?> scheduleAtFixedRate(Runnable command, long delay, long period, TimeUnit unit);

	boolean inEventLoop();

	boolean inEventLoop(Thread thread);

	/**
	 * 等待策略： Yield (建议使用 Gentle)
	 * 
	 * @return
	 */
	static EventLoop newEagerEventLoop() {
		return new SingleThreadEventLoop();
	}

	/**
	 * 等待策略： Wakeup
	 * 
	 * @return
	 */
	static EventLoop newGentleEventLoop() {
		return new SingleThreadEventLoop(new WakeupWaitStrategy());
	}

	/**
	 * 等待策略： Wakeup
	 * 
	 * @return
	 */
	static EventLoop newGentleEventLoop(ThreadFactory factory) {
		return new SingleThreadEventLoop(factory, new WakeupWaitStrategy());
	}

	/**
	 * 等待策略： Blocking
	 * 
	 * @return
	 */
	static EventLoop newTryBestEventLoop() {
		return new SingleThreadEventLoop(new BlockingWaitStrategy());
	}

	/**
	 * 等待策略： Blocking
	 * 
	 * @return
	 */
	static EventLoop newTryBestEventLoop(ThreadFactory factory) {
		return new SingleThreadEventLoop(factory, new BlockingWaitStrategy());
	}
}
